package com.juzipi.framework.security.handler;

import com.juzipi.common.constant.json.ResultCode;
import com.juzipi.common.tools.Result;
import com.juzipi.common.tools.ResultTool;
import com.juzipi.common.utils.json.JsonAuthentication;
import com.juzipi.framework.web.service.TokenService;
import com.juzipi.inter.domain.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功
 * @Explain
 */

@Component
public class MyAuthenticationSuccessHandler extends JsonAuthentication implements AuthenticationSuccessHandler {


    @Autowired
    private TokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //登陆成功就生成token返回
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token = tokenService.createToken(loginUser);
        Result result = ResultTool.successCustomize(ResultCode.LOGIN_SUCCESSFULLY, token);

        this.WriteJson(httpServletRequest,httpServletResponse,result);
    }

}
